package br.com.lsi.dao;

import java.util.ArrayList;
import java.util.List;

import javax.transaction.Transaction;

import org.apache.log4j.Logger;
import org.hibernate.Session;

import br.com.lsi.Util.HibernateUtil;
import br.com.lsi.repositorio.Repositorio;

public abstract class GenericDao<T> implements Repositorio<T> {

	private Session session;
	private Transaction trans;
	private Class<T> classe;
	private List<T> lista = new ArrayList<T>();
	private Logger logger = Logger.getLogger(GenericDao.class);

	public GenericDao(Class<T> classe) {
		this.classe = classe;
	}

	public void salvar(T generic) {			
		try {
			this.trans = (Transaction) getCurrentSession().beginTransaction();
			getCurrentSession().save(generic);
			commit();
		} catch (Exception e) {				
			rollback();
			logger.error(e.getMessage());
			e.printStackTrace();				
		}
	}

	public void deletar(T generic) {
		try {
			T novo = buscar(generic);
			this.trans = (Transaction) getCurrentSession().beginTransaction();
			getCurrentSession().delete(novo);
			commit();
		} catch (Exception e) {
			rollback();
			logger.error(e.getMessage());
		}
	}
	public T buscar(T entity) {

		long id = entity.hashCode();
		for (T t : lista) {

			if (id == t.hashCode())
				entity = t;
		}
		return entity;
	}

	public void alterar(T generic) {
		T novo = buscar(generic);
		try {
			trans = (Transaction) getCurrentSession().beginTransaction();
			getCurrentSession().update(novo);
			getCurrentSession().flush();
			commit();
		} catch (Exception e) {
			logger.error(e.getMessage());
			rollback();
		} 
	}

	public List<T> listar() {
		try {
			lista = getCurrentSession().createCriteria(classe).list();
		} catch (Exception e) {
			logger.error(e.getMessage());
			rollback();
		}
		return lista;
	}

	public Session getCurrentSession() {
		return this.session;
	}

	public void openSession() {
		this.session = HibernateUtil.getSessionFactory().openSession();
	}

	public void closeSession() {
		getCurrentSession().close();
	}

	public Transaction commit() {
		return this.trans;
	}

	public Transaction rollback(){
		return this.rollback();
	}
}
